<template>
  <div class="container-image">
      <el-card>
          <!-- 头部 -->
        <div slot="header">
            <my-bread>素材管理</my-bread>
        </div>
        <!-- 按钮 -->
        <div class="btn-box">
            <el-radio-group @change="toggleList()" v-model="reqParams.collect" size="small">
                <!-- label 属性单个按钮的值，当你选中点击后，这个值赋值给reqParams.collect -->
                <!-- label当你el-radios-button 组件中没有文字说明是，默认lable的值 -->
                <el-radio-button :label="false">全部</el-radio-button>
                <el-radio-button :label="true">收藏</el-radio-button>
            </el-radio-group>
            <el-button @click="openDialog" style="float:right" size="small" type="success">添加素材</el-button> 
        </div>
        
        <!-- 列表容器 -->
        <div class="list-box">
            <div class="item-box" v-for="item in images" :key="item.id">
                <img :src="item.url" alt/>
                <div class="option" v-if="!reqParams.collect">
                    <span @click="toggleStatus(item)" class="el-icon-star-off" :class="{'red':item.is_collected}"></span>
                    <span @click="delImage(item.id)" class="el-icon-delete"></span>
                </div>
            </div>
        </div>
            <!-- 分页 -->
            <el-pagination
                background
                layout="prev, pager, next"
                :total="total"
                :page-size="reqParams.per_page"
                :current-page="reqParams.page"
                @current-change="changePager">
            </el-pagination>
      </el-card> 

      <!-- 对话框 -->
        <el-dialog
            title="上传素材"
            :visible.sync="dialogVisible"
            width="300px">  
            <!-- 上传组件-->
            <el-upload
                class="avatar-uploader"
                action="http://ttapi.research.itcast.cn/mp/v1_0/user/images"
                name="image"
                :headers="headers"
                :on-success="uploadSuccess"
                :show-file-list="false">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-dialog>
  </div>
</template>

<script>
import auth from '@/utils/auth'
export default {
    name:"page-image",
    data(){
        return {
            //上传的请求头对象
            headers:{Authorization:`Bearer ${auth.getUser().token}`},
            //查询条件
            reqParams: {
                //是否查的收藏，true查询收藏图片，false查询全部
                collect:false,
                page:1,
                per_page:10,
            },
            //素材列表
            images:[],
            //总条数
            total:0,
            //控制对话框显示隐藏
            dialogVisible:false,
            //对话框
            imageUrl:null
        }
    },
    created(){
        this.getImages()
    },
    methods:{
        //上传成功 response是上传成功后后台返回数据
        uploadSuccess(response){
            //提示 + 预览
            // console.log(response);
            this.$message.success('上传素材成功')
            this.imageUrl = response.data.url
            //3s后：关闭对话框 + 更新列表
            window.setTimeout(()=>{
                 this.dialogVisible=false,
                 this.getImages()
            },3000)
        },

        //添加素材
        openDialog(){
            this.dialogVisible = true
            // 再次打开对话框，为空--清除预览图
            this.imageUrl=null
        },
        //进行：添加收藏 || 取消收藏
        async toggleStatus(item){
            try{
                //修改后状态
                const updateStatus = !item.is_collected
                await this.$http.put(`user/images/${item.id}`,{
                    //和当前图片状态取反即可，当前已收藏---》取消收藏  当前未收藏-->添加收藏
                    collect:updateStatus
                })
                 //成功提示
                this.$message.success(updateStatus ? '添加收藏成功' : '取消收藏成功')
                //根据修改后的状态,修改红色，白色--修改图片数据对应的状态is_collected
                item.is_collected = updateStatus
            }catch(e){
                //失败提醒
                this.$message.error(updateStatus?'添加收藏失败' : '取消收藏失败')
            }          
        },
        //删除素材
        delImage(id){
            //确认框
            this.$confirm('此操作将永久删除该图片, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then( async () => {
                //点击确认
                try{
                    //删除请求
                    await this.$http.delete(`user/images/${id}`)
                    this.$message.success('删除素材成功')
                    this.getImages()
                } catch(e){
                    this.$message.error('删除素材失败');
                    
                }
            }).catch(() => {
                //不处理         
            });
        },
        //切换全部和收藏
        toggleList(){
            this.reqParams.page = 1
            this.getImages()
        },
        //切换分页
        changePager(newPage){
            this.reqParams.page = newPage
            this.getImages()
        },
        //获取图片素材
        async getImages(){
            const res = await this.$http.get('user/images',{params: this.reqParams })
            // console.log(res);
            this.images = res.data.data.results
            //设置总条数
            this.total = res.data.data.total_count
        }
    }
}
</script>

<style scoped lang="less">
.list-box{
    margin-top: 20px;
    width: 100%;
    .item-box {
        display: inline-block;
        width: 20%;
        height: 180px;
        margin-bottom: 20px;
        margin-right: 50px;
        border: 1px solid #ddd;
        position: relative;
        img{
            display: block;
            width: 100%;
            height: 100%;
        }
        .option {
            width: 100%;
            height: 30px;
            position: absolute;
            left: 0;
            bottom: 0;
            background: rgba(0,0,0,0.3);
            text-align: center;
            line-height: 30px;
            span {
                color: #fff;
                margin: 0 35px;
                //不加&解析后：span  .red{} 后代选择器
                //加上&解析后：span.red{}  交集选择器
                &.red{
                    color: red;
                }
            }
        }
    }
}
</style>

